package com.example.springblog.Utils;

import com.example.springblog.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JWTUtils {
    public static final long JWT_EXPIRATION = 60*60*1000;

    public static final String secretStr = "nXeAgEiZZqIOPqiydZmmKGHq2AB+96/9Mikgvzs0ya4=";
    //转化为key类型
    public static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));

    //生成一个令牌
    public static String genJWT(Map<String,Object> claim){
        String token = Jwts.builder().setClaims(claim).
                setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION)).
                signWith(key).
                compact();
        return token;
    }

    //解析令牌
    public static Claims parseJWT(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        //解析失败与成功的情况
        Claims claims;
        try {
           claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            return null;
        }
        return claims;
    }

    //从token获取信息
    public static Integer getIDByToken(String token){
        Claims claims = parseJWT(token);
        Integer id = (Integer) claims.get(Constants.ID);
        if(id > 0){
            return id;
        }
        return null;
    }

}
